package com.cmpe451.nutty.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;

import com.cmpe451.nutty.model.User;
import com.cmpe451.nutty.so.GuiUser;
import com.cmpe451.nutty.utils.MyLogger;

/**
 * The base controller contains necessary and common functions for other controllers.
 * @author CmpE Group 2 Fall 2014 nuttyconfirmation@gmail.com
 * @version 2.0, January 2015
 */
public class BaseController {
	protected MyLogger logger = MyLogger.getLogger(getClass());

	/**
	 * This function finds the currently logged in user.
	 * @return currently logged in user. If no one is logged in, returns null
	 */
	protected GuiUser getUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null) {
			Object principal = authentication.getPrincipal();
			if (principal instanceof GuiUser) {
				return (GuiUser) principal;
			}
		}
		return null;
	}


	/**
	 * @param model each page can access the sitename and the current user through this function.
	 */
	protected void putGlobalAttributes(Model model) {
		model.addAttribute("siteName");
		model.addAttribute("currentUser", getUser());
	}

}
